//
//  Common.m
//  Zhiche-Carriage
//
//  Created by Code_浅蓝 on 17/4/18.
//  Copyright © 2017年 Code_JM. All rights reserved.
//

#import "Common.h"

#import <AFNetworking/AFNetworking.h>

#import "UIImageView+WebCache.h"

#import <Masonry.h>

#import <SystemConfiguration/SystemConfiguration.h>

#import "MBProgressHUD.h"

#import "LoginViewController.h"
#import "Header.h"
static Common *sharedCommon = nil;
 
@implementation Common
{
    DownloadFinishedBlock _finishedBlock;
    DownloadFailedBlock _failedBlock;
}
+ (Common *)shared{

    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        sharedCommon = [[Common alloc] init];
    });
    return sharedCommon;
}


///HTTP GET
+(void)requestWithUrlString:(NSString *)urlString
                contentType:(NSString *)type
                   finished:(DownloadFinishedBlock)finishedBlock
                     failed:(DownloadFailedBlock)failedBlock{
    
    AFHTTPRequestOperationManager *manager  = [AFHTTPRequestOperationManager manager];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:type,nil];
    
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = YES;
    
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *string = [user objectForKey:login_token];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    
    if (string.length > 0) {
        
        [manager.requestSerializer setValue:string forHTTPHeaderField:@"Authorization"];
     
    }
    
    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //可以进行一些其他操作，比如将网络数据NSData写到本地路径
        //执行一些其他操作后，再调用自己的block，方便对程序进行扩展
        
        
        if ([responseObject[@"messageCode"] isEqual:[NSNull null]]) {
            
            
        } else {
            
            if (![responseObject[@"success"] boolValue] && [responseObject[@"messageCode"] isEqualToString:@"5004"]) {
                
                UIViewController *viewC = [[[UIApplication sharedApplication] keyWindow] rootViewController];
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:responseObject[@"message"] preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    //                    [user setObject:nil forKey:login_token];
                    
                    LoginViewController *loginVC = [[LoginViewController alloc]init];
                    UINavigationController * loginNC = [[UINavigationController alloc]initWithRootViewController:loginVC];
                    
                    [viewC presentViewController:loginNC animated:YES completion:nil];
                    
                }];
                
                [alert addAction:action1];
                
#pragma mark push方法跟这一样，只是变变写法
                
                
            } else {
                
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                NSString *string = [user objectForKey:login_token];
                
                
                if (string.length > 0) {
                    
                    [manager.requestSerializer setValue:string forHTTPHeaderField:@"Authorization"];
                    
                }
            }
        }
        
        finishedBlock(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        //当出现错误信息是 弹出提示框
        //        [Common showAlertViewAndAnimated:YES andString:error.localizedDescription];
        [Common showAlertViewAndAnimated:YES andString:@"系统维护中"];
        
        
        failedBlock(error.localizedDescription);
    }];
}


///HTTP Post
+ (void)afPostRequestWithUrlString:(NSString *)urlString
                            parms:(NSDictionary *)dic
                    finishedBlock:(DownloadFinishedBlock)finished
                      failedBlock:(DownloadFailedBlock)failed{
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = YES;
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *string = [user objectForKey:login_token];
    
    
    if (string.length > 0) {
        
        [manager.requestSerializer setValue:string forHTTPHeaderField:@"Authorization"];
        
    }
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];

    [manager POST:urlString parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //调用自己定义的block
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        
        if ([dictionary[@"messageCode"] isEqual:[NSNull null]]) {
            
            finished(responseObject);
            
        } else {
            
            if (![dictionary[@"success"] boolValue] && [dictionary[@"messageCode"] isEqualToString:@"5004"]) {
                
                UIViewController *viewC = [[[UIApplication sharedApplication] keyWindow] rootViewController];
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:responseObject[@"message"] preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    //                [user setObject:nil forKey:login_token];
                    LoginViewController *loginVC = [[LoginViewController alloc]init];
                    UINavigationController * loginNC = [[UINavigationController alloc]initWithRootViewController:loginVC];
                    
                    [viewC presentViewController:loginNC animated:YES completion:nil];
                    
                }];
                
                [alert addAction:action1];
                
            } else {
                
                finished(responseObject);
                
            }
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //当出现错误信息是 弹出提示框
        //        [Common showAlertViewAndAnimated:YES andString:error.localizedDescription];
        [Common showAlertViewAndAnimated:YES andString:@"系统维护中"];
        
        
        //捕捉错误信息
        failed(error.localizedDescription);
    }];
}

///HTTP Post
- (void)afPostRequestWithUrlString:(NSString *)urlString
                             parms:(NSDictionary *)dic
                     finishedBlock:(DownloadFinishedBlock)finished
                       failedBlock:(DownloadFailedBlock)failed{
    if (_finishedBlock!=finished) {
        _finishedBlock = nil;
        _finishedBlock = finished;
    }
    if (_failedBlock!=failed) {
        _failedBlock = nil;
        _failedBlock = failed;
    }
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];
    securityPolicy.allowInvalidCertificates = YES;
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];

    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *string = [user objectForKey:login_token];
    
    if (string.length > 0) {
        
        [manager.requestSerializer setValue:string forHTTPHeaderField:@"Authorization"];
        
    }
    
    [manager POST:urlString parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //调用自己定义的block
        
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        
        if ([dictionary[@"messageCode"] isEqual:[NSNull null]]) {
            
            finished(responseObject);
            
        } else {
            
            if (![dictionary[@"success"] boolValue] && [dictionary[@"messageCode"] isEqualToString:@"5004"]) {
                
                UIViewController *viewC = [[[UIApplication sharedApplication] keyWindow] rootViewController];
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:responseObject[@"message"] preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    
                    //                [user setObject:nil forKey:login_token];
                    
                    LoginViewController *loginVC = [[LoginViewController alloc]init];
                    UINavigationController * loginNC = [[UINavigationController alloc]initWithRootViewController:loginVC];
                    
                    [viewC presentViewController:loginNC animated:YES completion:nil];
                    
                }];
                
                [alert addAction:action1];
                
            } else {
                
                finished(responseObject);
                
            }
            
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        //当出现错误信息是 弹出提示框
        //        [Common showAlertViewAndAnimated:YES andString:error.localizedDescription];
        [Common showAlertViewAndAnimated:YES andString:@"系统维护中"];
        
        //捕捉错误信息
        _failedBlock(error.localizedDescription);
    }];
}

///HTTP 上传图片
//dic 中放除图片以外的其他参数, data 图片转换的NSData key 为图片对应的key：pis
- (void)afUploadImageWithUrlString:(NSString *)urlString
                             parms:(NSDictionary *)dic
                         imageData:(NSData *)data
                          imageKey:(NSString *)key
                     finishedBlock:(DownloadFinishedBlock)finished
                       failedBlock:(DownloadFailedBlock)failed{
    if (_finishedBlock!=finished) {
        _finishedBlock = nil;
        _finishedBlock = finished;
    }
    if (_failedBlock!=failed) {
        _failedBlock = nil;
        _failedBlock = failed;
    }
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    //上传图片的post方法
    [manager POST:urlString parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

        [formData appendPartWithFileData:data name:key fileName:@"test.png" mimeType:@"image/png"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        _finishedBlock(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        _failedBlock(error.localizedDescription);
    }];
}



///判断是否登录
+ (void)isLogin:(UIViewController *)target
        andPush:(UIViewController *)next{
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString *string = [userDefaults objectForKey:@"login"];
    
    if (string == nil ) {
        
        LoginViewController *loginVC = [[LoginViewController alloc]init];
        UINavigationController * loginNC = [[UINavigationController alloc]initWithRootViewController:loginVC];
        
        [target presentViewController:loginNC animated:YES completion:nil];
        
    }  else {
        [target.navigationController pushViewController:next animated:YES];
    }
}

///判断用户类型
+ (BOOL)judgeUsertype{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    NSString *string = [user objectForKey:@"userType"];
    
    if ([string isEqualToString:@"50"])
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

///创建一个消息提示框
+ (void)showAlertViewAndAnimated:(BOOL)animated
                       andString:(NSString *)string{
    UIWindow *window = [[UIApplication sharedApplication].delegate window];
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    view.backgroundColor = [UIColor blackColor];
    [window addSubview:view];
    
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, window.frame.size.width/2.0, 20)];
    label.text = string;
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:15];
    label.numberOfLines = 0;
    label.textAlignment = NSTextAlignmentCenter;
    CGRect rect = [label.text boundingRectWithSize:CGSizeMake(window.frame.size.width/2.0, 200) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil];
    label.frame = CGRectMake(15, 5, rect.size.width + 20, rect.size.height + 10);
    view.frame = CGRectMake(0, 0, rect.size.width + 50, rect.size.height + 20);
    [view addSubview:label];
    view.layer.cornerRadius = 10;
    
    view.center = window.center;
    
    if (animated) {
        view.alpha = 0;
        [window addSubview:view];
        
        [UIView animateWithDuration:0.3 animations:^{
            view.alpha = 0.78;
        } completion:^(BOOL finished) {
            
            
        }];
    }
    else {
        [window addSubview:view];
    }
    
    //延迟执行
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [view removeFromSuperview];
        
    });
    
}

//提示框
- (UIImageView*)createUIImage:(NSString *)title andDelay:(float)delay {
    
    UILabel * label =[[UILabel alloc]init];
    label.text = title;
    label.tag = 88;

    label.textAlignment = NSTextAlignmentCenter;
    UIFont *fnt = [UIFont fontWithName:@"HelveticaNeue" size:FontOfSize15];
    label.textColor = [UIColor whiteColor];
    CGSize size = [label.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:fnt,NSFontAttributeName, nil]];
    
    // 名字的H
    CGFloat nameH = size.height;
    // 名字的W
    CGFloat nameW = size.width;
    
    label.frame =CGRectMake(0, 0, nameW, nameH);
    label.font = Font(FontOfSize15);

    UIImageView * imageCollect = [[UIImageView alloc]init];
    imageCollect.image = [UIImage imageNamed:@"project_product_collect_jiaohu"];
    imageCollect.frame = CGRectMake(0, 0, 90+label.frame.size.width, 41);
    imageCollect.alpha = 0.5;
    imageCollect.tag = 100;
    
    [imageCollect addSubview:label];
    //收藏成功提示
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(imageCollect.mas_centerX);
        make.centerY.equalTo(imageCollect.mas_centerY);
    }];
    
    [self performSelector:@selector(CollectDissMi:) withObject:imageCollect afterDelay:delay];
    return imageCollect;
}

- (void)CollectDissMi:(UIImageView *)sender{
    
    [sender  removeFromSuperview];
}


-(UITextField*)createField:(NSString*)placeholder andTag:(int)tag andFont:(double)font{
    UITextField * field =[[UITextField alloc]init];
    field.frame = CGRectMake(0, 0, Main_Width-91, 50);
    field.delegate = self;
    field.userInteractionEnabled = YES;
    field.textAlignment = NSTextAlignmentLeft;
    field.keyboardType = UIKeyboardTypeDefault;
    //    field.returnKeyType = UIReturnKeySend;
    field.tag = tag;
    field.placeholder =placeholder;
    //    field.text = placeholder;
    field.textColor = littleBlackColor;
    field.font =Font(font);
    return field;
}

//校验用户手机号码
+ (BOOL)validateUserPhone:(NSString *)str
{
    NSRegularExpression *regularexpression = [[NSRegularExpression alloc]
                                              initWithPattern:@"^1[3|4|5|7|8][0-9][0-9]{8}$"
                                              options:NSRegularExpressionCaseInsensitive
                                              error:nil];
    NSUInteger numberofMatch = [regularexpression numberOfMatchesInString:str
                                                                  options:NSMatchingReportProgress
                                                                    range:NSMakeRange(0, str.length)];
    if(numberofMatch > 0)
    {
        return YES;
    }
    return NO;
}

-(NSString *)backString:(NSString *)string
{
//    NSString * str = [NSString stringWithFormat:@"%@",string];
    if ([string isEqual:[NSNull null]]) {
        return @"";
    } else {
        return string;
    }
}

+(BOOL)compareDate:(NSString*)date01 withDate:(NSString*)date02{
    
    BOOL ci;
    
    NSDateFormatter *df = [[NSDateFormatter alloc]init];
    [df setDateFormat:@"yyyy-MM-dd"];
    
    NSDate *dt1 = [[NSDate alloc]init];
    NSDate *dt2 = [[NSDate alloc]init];
    
    dt1 = [df dateFromString:date01];
    dt2 = [df dateFromString:date02];
    
    NSComparisonResult result = [dt1 compare:dt2];
    
    switch (result)
    
    {
            //date02比date01大
            
        case NSOrderedAscending: ci=NO;break;
            
            //date02比date01小
            
        case NSOrderedDescending: ci=YES;break;
            
            //date02=date01
            
        case NSOrderedSame: ci=YES;break;
            
        default: NSLog(@"erorr dates %@, %@", dt2, dt1);break;
            
    }
    
    return ci;
}


@end
